/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.constants.dd.DDSQLListType;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.entity.QueryInfo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.meta.service.MetaDictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-09-17 13:45
 * @description: SQL字典项服务实现
 */
@Service("metaSqlDictionaryItemService")
public class MetaSqlDictionaryItemServiceImpl implements MetaDictionaryItemService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private SystemVariableRpcService systemVariableRpcService;

    @Override
    public List<JSONTreeNode> getDdItems(DynaBean dictionary, Map<String, String> params, QueryInfo queryInfo, Boolean en) {
        if(dictionary == null){
            throw new PlatformException("获取字典为空！",PlatformExceptionEnum.UNKOWN_ERROR);
        }

        //非列表字典抛出异常
        if (!DDType.SQL.equals(dictionary.getStr("DICTIONARY_DDTYPE"))) {
            throw new PlatformException("获取字典项异常，非法的字典类型" + dictionary.getStr("DICTIONARY_DDTYPE"), PlatformExceptionEnum.UNKOWN_ERROR);
        }

        //声明变量集合，用于解析whereSql的通配符
        Map<String, Object> ddMap = systemVariableRpcService.formatCurrentUserAndCachedVariables();
        if (params != null) {
            ddMap.putAll(params);
        }

        //构建sql
        String querySql = StringUtil.getDefaultValue(queryInfo.getWhereSql(), "");
        String ddWhereSql = dictionary.getStr("DICTIONARY_WHERESQL", "");
        if (StringUtil.isNotEmpty(ddWhereSql)) {
            querySql += ddWhereSql;
        }
        if (StringUtil.isNotEmpty(querySql)) {
            querySql = StringUtil.parseKeyWord(querySql, ddMap);
        }

        String sql = dictionary.getStr("DICTIONARY_SQL");
        String sqlConfig = dictionary.getStr("DICTIONARY_SQLPZXXLB");
        if (StringUtil.isEmpty(sql) || StringUtil.isEmpty(sqlConfig)) {
            throw new PlatformException("SQL类型字典配置错误！", PlatformExceptionEnum.UNKOWN_ERROR);
        }

        sql = StringUtil.parseKeyWord(sql, ddMap);
        if (StringUtil.isNotEmpty(querySql)) {
            sql += querySql;
        }
        String order = dictionary.getStr("DICTIONARY_ORDER");
        if(Strings.isNullOrEmpty(order)){
            sql += " " + order;
        }
        //构建映射结果
        //树形字段配置
        JSONObject config = (JSONObject) JSON.parse(sqlConfig);
        Map<String, Object> sqlConfigMap = new HashMap();
        for (String key : config.keySet()) {
            String value = config.getString(key);
            sqlConfigMap.put(key, value);
        }
//        List<Map> sqlConfigMap = JsonBuilder.getInstance().fromJsonArray(sqlConfig);
//        List<String> mappingResultList =  buildStandardDdValue(sqlConfigMap);
        String id = sqlConfigMap.get("idField").toString();
        String name = sqlConfigMap.get("nameField").toString();
        String code = sqlConfigMap.get("codeField").toString();
        String iconCls = sqlConfigMap.get("iconClsField").toString();

        //构建列表
        List<Map<String, Object>> values = metaService.selectSql(sql);
        List<JSONTreeNode> lists = new ArrayList();
        JSONTreeNode ddValue;
        String rootId = ConstantVars.TREE_ROOT;
        for (Map<String,Object> eachMap : values) {
            ddValue = new JSONTreeNode();
            ddValue.setParent(rootId);
            if(sqlConfigMap == null || (Strings.isNullOrEmpty(id) && Strings.isNullOrEmpty(name) && Strings.isNullOrEmpty(code) && Strings.isNullOrEmpty(iconCls))){
                ddValue.setBean(eachMap);
                ddValue.setLeaf(true);
                lists.add(ddValue);
                continue;
            }
            if(!Strings.isNullOrEmpty(id)){
                ddValue.setId(eachMap.get(id) == null?null:eachMap.get(id).toString());
            }
            if(!Strings.isNullOrEmpty(name)){
                ddValue.setText(eachMap.get(name) == null?null:eachMap.get(name).toString());
            }
            if(!Strings.isNullOrEmpty(code)){
                ddValue.setCode(eachMap.get(code) == null?null:eachMap.get(code).toString());
            }
            if(!Strings.isNullOrEmpty(iconCls)){
                ddValue.setIcon(eachMap.get(iconCls) == null?null:eachMap.get(iconCls).toString());
            }

            ddValue.setLeaf(true);
            ddValue.setBean(eachMap);
            lists.add(ddValue);
        }
        return lists;
    }

    /**
     * 构建标准的字典映射配置顺序，如下：
     * 1：ID
     * 2：NAME
     * 3: CODE
     * 4: ICONCLS
     * @return
     */
    private List<String> buildStandardDdValue(List<Map> sqlConfigMap){
        String id = null;
        String name = null;
        String code = null;
        String iconCls = null;

        for (Map field : sqlConfigMap) {
            String fieldType = field.get("code") + "";
            String fieldName = field.get("value") + "";
            if(DDSQLListType.ID.equals(fieldType)){
                id = fieldName;
            }
            if(DDSQLListType.NAME.equals(fieldType)){
                name = fieldName;
            }
            if(DDSQLListType.CODE.equals(fieldType)){
                code = fieldName;
            }
            if(DDSQLListType.ICONCLS.equals(fieldType)){
                iconCls = fieldName;
            }
        }

        return Lists.newArrayList(id,name,code,iconCls);

    }

}
